package com.sdp.lease.controller;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.sdp.core.bizc.db.Query;
import com.sdp.core.bizc.utils.UniqueCheckTools;
import com.sdp.core.bizc.vo.DataCenter;
import com.sdp.core.bizc.vo.Result;
import com.sdp.lease.cache.LeaseCleanCache;
import com.sdp.lease.db.l_supplier.entity.LSupplier;
import com.sdp.lease.db.l_supplier.service.ILSupplierService;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author zsp
 * @since 2024-07-25
 */
@RestController
@RequestMapping("/LSupplierController")
public class LSupplierController {

	@Autowired
	private Query query;
	
	@Autowired
	private ILSupplierService iLSupplierService;
	
	@Autowired
	private UniqueCheckTools uniqueCheckTools;
	
	@Autowired
	private LeaseCleanCache leaseCleanCache;
	
	@PostMapping(value = "/page")
	public Result<?> page(@RequestBody DataCenter dataCenter) {
		return Result.ok(query.page(iLSupplierService, LSupplier.class, dataCenter));
	}
	
	@PostMapping(value = "/save")
	@Transactional(rollbackFor=Exception.class)
	public Result<?> save(@RequestBody LSupplier supplier) {
		if(supplier==null) {
			return Result.error("供应商息为空");
		}
		if(StringUtils.isEmpty(supplier.getKeyId())) {
			Result<?> r = uniqueCheckTools.isUniqueSingle(iLSupplierService, LSupplier.class, new String[] {"supplierUscc"}, "keyId", supplier, null, false);
			if(r==null || !r.isSuccess()) {
				return Result.error("统一社会信用代码不能重复");
			}
			iLSupplierService.save(supplier);
		}else {
			Result<?> r = uniqueCheckTools.isUniqueSingle(iLSupplierService, LSupplier.class, new String[] {"supplierUscc"}, "keyId", null, supplier, false);
			if(r==null || !r.isSuccess()) {
				return Result.error("统一社会信用代码不能重复");
			}
			iLSupplierService.updateById(supplier);
		}
		leaseCleanCache.cleanSupplierCache();
		return Result.ok();
	}
	
	
	@GetMapping(value = "/getSupplier")
	public Result<?> getSupplier(@RequestParam(name="keyId",required=true) String keyId) {
		if(StringUtils.isEmpty(keyId)) {
			return Result.error("供应商信息不完整");
		}
		LSupplier supplier = iLSupplierService.getById(keyId);
		if(supplier==null) {
			return Result.error("选择的供应商不存在");
		}
		
		return Result.ok(supplier);
	}
}

